package com.rem.rabbitmq.boot;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author Rem
 * @date 2022/1/5
 */
@Component
@Slf4j
public class MyCallBack implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //依赖注入rabbitTemplate之后再设置它的回调对象
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * 回调接口
     * 当发送的消息传给不存在的交换机 ack为false
     * 当发送的消息传给存在的交换机，但是routingkey错误时 ack依然是true 表示交换机收到了消息但是是路由出错
     *
     * @param correlationData 发布确认基类
     * @param ack
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (correlationData != null) {
            String id = correlationData.getId();
            if (ack) {
                log.info("交换机已经收到id为:{}的消息", id);
            } else {
                log.warn("交换机还未收到id为:{}消息,由于原因:{}", id, cause);
            }
        }

    }

    /**
     * 只有消息不可到达时 才会回退消息
     * 回退消息
     *
     * @param returned
     */
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        String message = new String(returned.getMessage().getBody());
        log.error("消息{},被交换机{}退回，退回原因:{},路由key:{}",
                message, returned.getExchange(), returned.getReplyText(), returned.getRoutingKey());
    }
}